﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DCT.Huiteng.Utility.Miscellaneous;
using DCT.Huiteng.Utility.Config;
using DCT.Huiteng.Utility.Cache;
using System.IO;
using DCT.Huiteng.Utility;

namespace DCT.Huiteng.AdminSystem.Web.Codes
{
    /// <summary>
    /// 一般工具方法
    /// </summary>
    public static class GeneralToolCode
    {
        public static QueueExecution CreateQueueExecutionInstance() { 
            return  CreateQueueExecutionInstance(null);
        }

        public static QueueExecution CreateQueueExecutionInstance(string customLogTag)
        {
            QueueExecution qe = new QueueExecution();
            qe.LogExecuteTime = true;
            qe.LogEvent += (_sender, _e) =>
            {
                var logdata = _e.Data;
                if (!string.IsNullOrEmpty(customLogTag))
                {
                    logdata.Tag = customLogTag;
                }
                Logger.Instance.Log(logdata);
            };
            return qe;
        }

        private static KeyValueCache<IConfigParser> configCache = new KeyValueCache<IConfigParser>();

        public static IConfigParser LoadConfig(string name) {
            if (string.IsNullOrEmpty(name)) {
                throw new NullReferenceException("name is null or empty");
            }
            if (!name.EndsWith(".config")) {
                name += ".config";
            }

            return configCache.GetValue(name, delegate {
                //创建IConfigParser
                string path = "~/configs/" + name;
                string content = File.ReadAllText(HttpExtUtility.CurrentHttpContext.Server.MapPath(path));
                var cp = new XmlConfigParser();
                cp.Load(content);
                return cp;
            });
        }
    }
}